<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-form ref="query" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="名称">
              <i slot="label" class="el-icon-search" style="font-size:20px"></i>
              <el-input v-model="query.keywords" style="width:360px" placeholder="请输入名称搜索"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="是否限购">
              <el-select v-model="query.is_limit" placeholder="是否限购">
                <el-option label="全部" value></el-option>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="价格区间">
              <el-input v-model="query.lowPrice" style="width:200px" placeholder="低"></el-input>-
              <el-input v-model="query.heightPrice" style="width:200px" placeholder="高"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="分类">
              <el-select
                v-model="query.type"
                style="width:360px"
                @focus="getCategoryList"
                placeholder="请选择分类"
                :loading="optionLoading"
              >
                <el-option label="全部" value="0"></el-option>
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.class_name"
                  :value="item.class_id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="queryAsk">查询</el-button>
          <el-button @click="queryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
    </el-card>

    <!-- 表格 -->
    <el-card class="box-card">
      <img
        class="watermark"
        v-if="baseApi== 'https://testouhun.wm2177.com'"
        style="right: 0;"
        src="@/assets/watermark.png"
      />

      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-button type="primary" style="margin-bottom:20px" @click="batchAdd">批量添加</el-button>
      <el-button type="primary" style="margin-bottom:20px" @click="batchEdite=true">批量编辑</el-button>
      <el-button
        type="primary"
        style="margin-bottom:20px"
        :disabled="!batchEdite"
        @click="batchEditeSub"
      >确认编辑</el-button>
      <el-button
        type="primary"
        style="margin-bottom:20px"
        :disabled="!batchEdite"
        @click="cancelBatch"
      >取消编辑</el-button>
      <el-table
        @sort-change="sortChange"
        ref="table"
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" label="封面图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column align="center" prop="kc" label="库存">
          <template slot-scope="scope">
            <div v-if="!batchEdite">{{scope.row.kc}}</div>
            <div v-else>
              <el-input v-model="scope.row.kc"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="spec" label="规格名称"></el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="price" label="售价" sortable="custom">
          <template slot-scope="scope">
            <div v-if="scope.row.is_integral==0&&!batchEdite">{{scope.row.price}}</div>
            <div v-if="scope.row.is_integral==1&&!batchEdite">{{'-'}}</div>
            <div v-if="batchEdite">
              <el-input v-model="scope.row.price" :disabled="scope.row.is_integral==1"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="integral" label="积分价格" sortable="custom">
          <template slot-scope="scope">
            <div v-if="scope.row.is_integral==1&&!batchEdite">{{scope.row.integral}}</div>
            <div v-if="scope.row.is_integral==0&&!batchEdite">{{'-'}}</div>
            <div v-if="batchEdite">
              <el-input v-model="scope.row.integral" :disabled="scope.row.is_integral==0"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="is_limit" label="是否限购">
          <template slot-scope="scope">
            <div v-if="scope.row.is_limit==1&&!batchEdite">是</div>
            <div v-if="scope.row.is_limit==0&&!batchEdite">否</div>
            <el-select
              @change="isIntegral(scope.row)"
              v-if="batchEdite"
              v-model="scope.row.is_limit"
              placeholder="是否限购"
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="is_integral" label="是否积分购买">
          <template slot-scope="scope">
            <div v-if="scope.row.is_integral==1&&!batchEdite">是</div>
            <div v-if="scope.row.is_integral==0&&!batchEdite">否</div>
            <el-select
              @change="isIntegral(scope.row)"
              v-if="batchEdite"
              v-model="scope.row.is_integral"
              placeholder="请选择是否积分购买"
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sales_initial" label="初始销量">
          <template slot-scope="scope">
            <div v-if="!batchEdite">{{scope.row.sales_initial}}</div>
            <div v-if="batchEdite">
              <el-input v-model="scope.row.sales_initial"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="is_by" label="是否包邮">
          <template slot-scope="scope">
            <div v-if="scope.row.is_by==1&&!batchEdite">是</div>
            <div v-if="scope.row.is_by==0&&!batchEdite">否</div>
            <el-select v-if="batchEdite" v-model="scope.row.is_by" placeholder="请选择是否包邮">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" prop="add_time" label="添加时间" sortable="custom"></el-table-column>
        <el-table-column
          align="center"
          width="200"
          prop="update_time"
          label="更新时间"
          sortable="custom"
        ></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      title="商品库"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-form ref="drawquery" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="商品名称">
              <el-input v-model="drawquery.keywords" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="分类">
              <el-cascader
                v-model="drawquery.class_id"
                :options="dialogoptions"
                :props="{ checkStrictly: true,value:'id',label:'class_name' }"
                placeholder="请选择分类"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="drawqueryAsk">查询</el-button>
          <el-button @click="drawqueryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
      <el-table
        :data="goodsData"
        ref="sendmultipleTable"
        border
        tooltip-effect="dark"
        style="width: 100%;margin: 20px 0;"
        @selection-change="handleSelectionChange"
        :header-cell-style="{background:'#eee'}"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>

        <el-table-column align="center" prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column align="center" label="商品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="spec" label="规格"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="drawcurrentPage"
          :total="drawtotal"
          @current-change="drawcurrentChange"
        ></el-pagination>
      </div>
      <div style="text-align:right;margin-top:20px">
        <el-button type="primary" @click="goodsInfo">确定</el-button>
        <el-button @click="drawer=false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  commodityMangeList,
  commodityCategoryList,
  deleteMangeList,
  addMangeList,
  editeMangeList
} from '@/api/commodity'
import { parseTime } from '@/utils/index'
import { categoryList } from '@/api/product'
import { upload, productList } from '@/api/system'

export default {
  name: 'CommodityManage',
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        is_limit: undefined,
        keywords: '',
        type: '0',
        lowPrice: '',
        heightPrice: '',
        order_by: ''
      },
      tableData: [],
      options: [],
      loading: false,
      optionLoading: false,
      priceArr: [],
      // 分页数据
      drawtotal: 0,
      drawcurrentPage: 1,
      drawpageSize: 10,
      // 抽屉
      drawer: false,
      direction: 'rtl',
      //query
      drawquery: {
        keywords: '',
        class_id: ''
      },
      goodsData: [],
      goods: [],
      optionLoading: false,
      dialogoptions: [],
      batchEdite: false
    }
  },
  mounted() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    //获取列表
    async getList() {
      this.loading = true
      const res = await commodityMangeList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords,
        class_id: this.query.type,
        price: this.priceArr,
        order_by: this.query.order_by,
        is_limit: this.query.is_limit == '' ? undefined : this.query.is_limit
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.tableData = res.data
      this.tableData.forEach((item) => {
        if (item.add_time == 0) {
          item.add_time = '-'
        } else {
          item.add_time = parseTime(item.add_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
        if (item.update_time == 0) {
          item.update_time = '-'
        } else {
          item.update_time = parseTime(
            item.update_time,
            '{y}-{m}-{d} {h}:{i}:{s}'
          )
        }
      })
    },
    //获取分类列表
    async getCategoryList() {
      this.optionLoading = true
      const res = await commodityCategoryList({
        page: this.currentPage,
        limit: '999',
        keywords: ''
      })
      this.optionLoading = false
      this.options = res.data
      console.log(res)
    },
    // 表格操作
    async handleDel(row) {
      try {
        const res = await deleteMangeList({ id: row.id })
        console.log(res)
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error)
      }
    },
    handleEdite(row) {
      this.$router.push({
        name: 'CommodityManageEdite',
        query: { rows: row, type: '编辑' }
      })
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getList()
    },
    // 搜索列表
    queryAsk() {
      // 不可以一个有值一个没值
      if (!this.query.lowPrice && !this.query.heightPrice) {
        console.log(this.query)
        this.currentPage = 1
        this.priceArr = []
        this.getList()
      } else if (this.query.lowPrice && this.query.heightPrice) {
        this.priceArr = [this.query.lowPrice, this.query.heightPrice]
        console.log(this.query)
        this.currentPage = 1
        this.getList()
      } else if (!this.query.lowPrice || !this.query.heightPrice) {
        this.$message.error('请输入价格区间')
      }
      // console.log(this.query);
      // this.currentPage = 1;
      // this.getList();
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.query.heightPrice = ''
      this.query.lowPrice = ''
      this.priceArr = []
      // this.query.order_by = "";
      this.getList()
    },
    addList() {
      this.$router.push({
        name: 'CommodityManageEdite',
        query: { row: this.tableData[0], type: '添加' }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 排序
    sortChange({ column, prop, order }) {
      if (order == 'descending') {
        this.query.order_by = prop + ',' + 'desc'
        this.getList()
      } else if (order == 'ascending') {
        this.query.order_by = prop + ',' + 'asc'
        this.getList()
      }
    },
    // 商品库
    batchAdd() {
      this.getProductList()
      this.getCategary()
      this.drawer = true
    },
    async getProductList() {
      const res = await productList({
        page: this.drawcurrentPage,
        limit: this.drawpageSize,
        keywords: this.drawquery.keywords,
        class_id: this.drawquery.class_id,
        is_goods: '1'
      })
      console.log(res)
      this.goodsData = res.data
      this.drawtotal = res.count
    },
    // 获取商品分类
    async getCategary() {
      const res = await categoryList({
        page: 1,
        limit: 999,
        keywords: '',
        is_goods: '1'
      })
      console.log(res)
      this.dialogoptions = res.data
    },
    chooseGood() {
      this.drawer = true
      this.getProductList()
    },
    handleClose(done) {
      done()
    },
    // 搜索列表
    drawqueryAsk() {
      console.log(this.drawquery)
      this.drawquery.class_id =
        this.drawquery.class_id[this.drawquery.class_id.length - 1]
      this.drawcurrentPage = 1
      this.getProductList()
    },
    drawqueryReset() {
      this.resetForm('drawquery')
      this.drawtotal = 0
      this.drawcurrentPage = 1
      this.drawpageSize = 10
      this.drawquery.keywords = ''
      this.drawquery.class_id = ''
      this.getProductList()
    },
    //分页改变
    drawcurrentChange(current) {
      this.goods = []
      this.drawcurrentPage = current
      this.getProductList()
    },
    handleSelectionChange(val) {
      console.log(val)
      this.goods = []
      val.forEach((item) => {
        let id = JSON.stringify(item.class_id)
        let batch = {
          goods_name: item.goods_name,
          sort: '',
          class_id: item.classId,
          classId: id,
          is_index: '0',
          is_show: '1',
          kc: '500',
          is_by: '1',
          is_ys: '0',
          ys_time: '',
          sales_initial: '0',
          is_integral: '0',
          price: '1',
          integral: '0',
          img: item.img,
          imgs: [item.img],
          details: `<img src=${item.img}></img>`,
          spec: item.spec
        }
        this.goods.push(batch)
      })
      console.log(this.goods)
    },
    async goodsInfo() {
      console.log(this.goods)
      let sure = []
      for (let i = 0; i < this.goods.length; i++) {
        const element = this.goods[i]
        const res = await addMangeList({ ...element })
        if (res.st === 1) {
          sure.push(1)
        } else {
          sure.push(2)
          console.log(res)
        }
      }
      // this.goods.forEach(async item => {
      //   const res = await addMangeList({ ...item });
      // });

      if (!sure.includes(2)) {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.drawer = false
        this.getList()
      } else {
        this.$message.error('添加失败')
        this.drawer = false
        this.getList()
      }
    },
    // 是否积分支付
    isIntegral(item) {
      if (item.is_integral == 1) {
        item.price = 0
      } else {
        item.integral = 0
      }
    },
    // 批量编辑
    async batchEditeSub() {
      console.log(this.tableData)
      let sure = []

      for (let i = 0; i < this.tableData.length; i++) {
        const element = this.tableData[i]
        const res = await editeMangeList({ ...element })
        if (res.st === 1) {
          sure.push(1)
        } else {
          sure.push(2)
          console.log(res)
        }
      }

      if (!sure.includes(2)) {
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
        this.batchEdite = false
        this.getList()
      } else {
        this.$message.error('编辑失败')
        this.batchEdite = false
        this.getList()
      }
    },
    // 取消批量编辑
    cancelBatch() {
      this.batchEdite = false
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  // width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
// ::v-deep .el-drawer.rtl {
//   width: 650px !important;
//   overflow: auto;
// }
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 50% !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>